package cn.whale.pay.mq.callback;

import cn.whale.basic.utils.JSONResult;
import cn.whale.task.api.PayResultToMQApi;
import cn.whale.task.domain.MqLog;
import cn.whale.task.to.MQLogStatusUpdateTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
@Transactional
public class PayMsgConfirmCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private PayResultToMQApi payResultToMQApi;

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.debug("PayMsgConfirmCallback 消息投递回调，ACK={},cause={},correlationData={}",ack,cause,correlationData);
        if(!ack){
            String correlationDataId = correlationData.getId();
            JSONResult jsonResult = payResultToMQApi.updateStatusForMqLog(new MQLogStatusUpdateTo(MqLog.STATUS_ERROR,correlationDataId));
            log.error("修改支付结果MQ日志{},消息ID{}",jsonResult,correlationDataId);
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.debug("消息投递到队列失败message={},replyText={}",message,replyText);
        String correlationDataId = message.getMessageProperties().getHeaders().get("spring_returned_message_correlation").toString();
        JSONResult jsonResult = payResultToMQApi.updateStatusForMqLog(new MQLogStatusUpdateTo(MqLog.STATUS_ERROR,correlationDataId));
        log.error("修改支付结果MQ日志{},消息ID{}",jsonResult,correlationDataId);
    }


}
